/*
 * Copyright 2008 Sebastian Köhler
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package calyriumdc.gui;

import calyriumdc.ConnectionManager;
import calyriumdc.Crypto;
import calyriumdc.DownloadManager;
import calyriumdc.FavoriteUsers;
import calyriumdc.event.ChatEvent;
import calyriumdc.event.ChatListener;
import calyriumdc.event.NickEvent;
import calyriumdc.event.NickListener;
import calyriumdc.event.PrivateMessageEvent;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Random;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;

public class HubViewPanel extends javax.swing.JPanel {

    private int id;
    private HashMap<String, PrivateChatPanel> privatechats = new HashMap<String, PrivateChatPanel>();

    /** Creates new form HubView */
    public HubViewPanel(int id) {
        this.id = id;
        initComponents();
    }

    @Action
    public void sendText() {
        if (jTextField1.getText() != null && !jTextField1.getText().equals("")) {
            ConnectionManager.getInstance().sendText(id, jTextField1.getText());
        }
        jTextField1.setText("");
    }
    
    @Action
    public void openPrivateMessage() {
        int index = jTable1.getSelectedRow();
        if(index != -1) {
            String nick = (String) jTable1.getValueAt(index, 0);
            PrivateChatPanel tmp = new PrivateChatPanel(id, nick);
            privatechats.put(nick, tmp);
            jTabbedPane1.addTab(nick, tmp);
        }
    }
    
    @Action
    public void addFavoriteUser() {
        int row = jTable1.getSelectedRow();
        if (row == -1) {
            return;
        }
        String nick = (String) jTable1.getValueAt(row, 0);
        String hub = ConnectionManager.getInstance().getHubIp(id);
        FavoriteUsers.getInstance().addUser(nick, hub, false, false);
    }
    
    @Action
    public void getFileList() {
        int row = jTable1.getSelectedRow();
        if (row == -1) {
            return;
        }
        String nick = (String) jTable1.getValueAt(row, 0);
        DownloadManager.getInstance().addDownload(true, nick + new Random().nextInt() + ".xml.bz2", nick, id);
    }

    protected void reconnect() {
        id = ConnectionManager.getInstance().reconnect(id, getNickListener(), getChatListener());
    }

    protected NickListener getNickListener() {
        return new NickListener() {

            public void nickChanged(final NickEvent evt) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
                        if (evt.getIp().equals("")) {
                            String[] row = new String[7];
                            row[0] = evt.getNick();
                            row[1] = Crypto.getBytes(Long.parseLong(evt.getShare()));
                            row[2] = evt.getDescription();
                            row[3] = evt.getTag();
                            row[4] = evt.getSpeed();
                            row[5] = evt.getEmail();
                            row[6] = evt.getIp();
                            int rows = model.getRowCount();
                            for (int i = 0; i < rows; i++) {
                                if (model.getValueAt(i, 0).equals(row[0])) {
                                    model.removeRow(i);
                                    model.insertRow(i, row);
                                    return;
                                }
                            }
                            model.addRow(row);
                        } else {
                            int rows = model.getRowCount();
                            for (int i = 0; i < rows; i++) {
                                if (model.getValueAt(i, 0).equals(evt.getNick())) {
                                    model.setValueAt(evt.getIp(), i, 6);
                                    return;
                                }
                            }
                        }
                    }
                });
            }

            public void removeNick(final NickEvent evt) {
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
                        int rows = model.getRowCount();
                        for (int i = 0; i < rows; i++) {
                            if (model.getValueAt(i, 0).equals(evt.getNick())) {
                                model.removeRow(i);
                                return;
                            }
                        }
                    }
                });
            }
        };
    }

    protected ChatListener getChatListener() {
        return new ChatListener() {

            public void chatEvent(final ChatEvent evt) {
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        jTextArea1.append(evt.getData());
                    }
                });
            }

            public void privateMessage(final PrivateMessageEvent evt) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (privatechats.containsKey(evt.getUser())) {
                            privatechats.get(evt.getUser()).appendText(evt.getData());
                        } else {
                            PrivateChatPanel tmp = new PrivateChatPanel(id, evt.getUser());
                            privatechats.put(evt.getUser(), tmp);
                            jTabbedPane1.addTab(evt.getUser(), tmp);
                            tmp.appendText(evt.getData());
                        }
                    }
                });
            }
        };
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        jPopupMenu1.setName("jPopupMenu1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(calyriumdc.CalyriumDC.class).getContext().getActionMap(HubViewPanel.class, this);
        jMenuItem2.setAction(actionMap.get("openPrivateMessage")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jPopupMenu1.add(jMenuItem2);

        jSeparator1.setName("jSeparator1"); // NOI18N
        jPopupMenu1.add(jSeparator1);

        jMenuItem1.setAction(actionMap.get("getFileList")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(calyriumdc.CalyriumDC.class).getContext().getResourceMap(HubViewPanel.class);
        jMenuItem1.setFont(resourceMap.getFont("jMenuItem1.font")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        jPopupMenu1.add(jMenuItem1);

        jMenuItem3.setAction(actionMap.get("addFavoriteUser")); // NOI18N
        jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        jPopupMenu1.add(jMenuItem3);

        setName("Form"); // NOI18N

        jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.LEFT);
        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jSplitPane1.setDividerLocation(200);
        jSplitPane1.setDividerSize(4);
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setComponentPopupMenu(jPopupMenu1);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Shared", "Description", "Tag", "Connection", "E-mail", "IP"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jSplitPane1.setRightComponent(jScrollPane1);

        jPanel1.setName("jPanel1"); // NOI18N

        jButton1.setAction(actionMap.get("sendText")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        jTextField1.setText(resourceMap.getString("jTextField1.text")); // NOI18N
        jTextField1.setName("jTextField1"); // NOI18N
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField1KeyTyped(evt);
            }
        });

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane2.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1))
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jSplitPane1.setLeftComponent(jPanel1);

        jTabbedPane1.addTab(resourceMap.getString("jSplitPane1.TabConstraints.tabTitle"), jSplitPane1); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 660, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents
    private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped

    }//GEN-LAST:event_jTextField1KeyTyped

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            sendText();
        }
    }//GEN-LAST:event_jTextField1KeyPressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
